<template>
	<view class="page">
		<!-- 导航栏 -->
		<u-navbar title-color="#fff" back-icon-color="#ffffff" is-back="true" :background="background" :back-text-style="{ color: '#fff' }"
		 title="账号管理" back-icon-name="nav-back" title-size='40'>
			<view class="navbar-right" slot="right">
				<view class="dot-box right-item paddlr20 fo-white" @click="onEdit">{{navRightTxt}}</view>
			</view>
		</u-navbar>


		<!-- 占位 -->
		<view style="height: 20rpx;width: 100%;"></view>
		<!-- 账号列表 -->
		<view class="AccountBox bg-White">
			<template v-for="i in AccountList">
				<view class="AccountBox-item flex just-spa-bet ali-cen padd20" @click="onCheck(i)">
					<view class="AccountBox-item-left flex ali-cen">
						<text class="cuIcon-roundclose mr20" :class="{EditIconIsShow:editIcon}" @click.stop="onDelAccont(i)"></text>
						<view class="AccountBox-item-left-avar">
							<image class="yicon-80 radius50p" :src="i.Avatar ? i.Avatar : 'http://pic2.sc.chinaz.com/Files/pic/pic9/202002/hpic2119_s.jpg'"></image>
						</view>
						<view class="AccountBox-item-left-info flex flex-col ali-sta ml20">
							<view class="font-wei600 fo-32">{{i.Nickname ? i.Nickname :"洋盘小主"}}</view>
							<text class="fo-gray mt10">{{i.way?'QQ登录账户':i.Account}}</text>
						</view>
					</view>
					<view class="AccountBox-item-righjt" v-show="i.IsCheck && editIcon">
						<text class="cuIcon-check fo-40 fo-blue"></text>
					</view>
				</view>
				<view style="height: 1px;width: 90%; background-color: #EBEBEB; margin: 0 auto;"></view>
			</template>

			<!-- 添加账号 -->
			<view class="addAccount AccountBox-item flex just-spa-bet ali-cen padd20">
				<view class="AccountBox-item-left flex ali-cen">
					<text class="mr20"></text>
					<view class="AccountBox-item-left-avar">
						<view class="yicon-80 flex bg-WhiteSmoke radius50p relative">
							<text class="cuIcon-add fo-gray fo-50 center-center"></text>
						</view>

					</view>
					<view class="AccountBox-item-left-info flex flex-col ali-sta ml20" @click="onNavToAddAccount">
						<view class="fo-blue font-wei600 fo-34">添加账号</view>
					</view>
				</view>
				<view class="AccountBox-item-righjt"></view>
			</view>
		</view>
		<!-- 退出账号/程序 -->
		<view class=" exitBox bg-White mt40">
			<view class="padd40 fo-30" @click="onExitAccount">退出当前账号</view>
			<view style="height: 1px;width: 90%; background-color: #EBEBEB; margin: 0 auto;"></view>
			<!-- #ifdef APP-PLUS -->
			<view class="padd40 fo-30" @click="onExitApp">退出洋盘</view>
			<!-- #endif -->
		</view>
		<!-- 占位 -->
		<view style="height: 40rpx;width: 100%;"></view>


		<!-- 拟态框弹窗 -->
		<YModal :YModalShow.sync='YModalShow' title='提示' :content='YModalTxt' @SubmitOk='YModal_SubmitOk'></YModal>
	</view>
</template>

<script>
	import YModal from '@/common/components/Y-showModel/index.vue'
	import {API$SelPwd} from '@/common/API/HuanXinIM.js'
	import MD5 from '../../../common/Tools/md5.js'
	export default {
		name: "",
		components: {
			YModal
		},
		data() {
			return {
				background: {
					background: '#87ceeb'
				},
				YModalShow: false, //拟态框
				YModalTxt: '是否退出该账号？', // 拟态框提示内容
				navRightTxt: '编辑', // 顶部导航栏右上角文字
				editIcon: true, // 编辑图标是否显示
				CurrentSelDelAccountID: null, // 当前选中的要被删除的账号的下标id
				// 账号列表
				AccountList: []
			}
		},
		onLoad() {
			let AccountList = this.$pub.getStorageSync('AcclountList')
			this.AccountList = AccountList
			// console.log(this.$HuanxinIM)
		},
		methods: {
			// 跳转添加账号
			onNavToAddAccount(){
				this.$pub.naviTo('/pages/other/login/index')
			},
			// 导航栏编辑按钮
			onEdit() {
				this.editIcon = !this.editIcon
				this.navRightTxt = this.navRightTxt === '编辑' ? '完成' : "编辑"
			},
			// 选择账号
			async onCheck(e) {
				// 选中的是当前账号不做操作  || 编辑账号下不做操作
				if(this.$pub.getStorageSync('Token') === e.Token ||  this.navRightTxt === '完成') return
				
				/*
					本地切换
				*/ 
				this.AccountList.forEach(i =>this.$set(i, 'IsCheck', false))
				this.$pub.setStorageSync('Token',e.Token)	// 替换token
				this.$pub.setStorageSync('UserInfo',e.Info) // 替换用户的个人信息
				this.$pub.delStorageSync('StudyPlane')			// 清空操作
				this.$set(e, 'IsCheck', true)
				
				/*
					同步到缓存内
				*/
				this.$pub.setStorageSync('AcclountList',this.AccountList)
				
				
				let _id = this.$pub.getStorageSync('UserInfo')._id
				let Res_SelPwd = await API$SelPwd({_id})
				this.$HuanxinIM.close()
				uni.showLoading({mask:true,title:'切换中'})
				setTimeout( async()=>{
					uni.hideLoading()
					// 重新登录IM
					let {msg,data} = await this.$HuanxinIM.Login({
					    user:_id,
					    pwd: MD5(Res_SelPwd.data.pwd || Res_SelPwd.data.openid)  // 普通用户是账号密码登录  第三方是_idz账号opendid为密码
					})
					if(msg==='fail'){
						this.$pub.Toast('账号密码错误~',data)
						this.$pub.reLaunch('/pages/other/login/index')
					}
					this.$pub.setStorageSync('HuanXinInfo',data)
					this.$pub.reLaunch('/pages/index/index')
				},1500)
				
			},
			// 退出程序
			onExitApp() {
				// #ifdef APP-PLUS  
				plus.runtime.quit();
				this.$HuanxinIM.close()
				// #endif
			},
			// 退出当前账号(删除当前账号缓存)
			onExitAccount() {
				this.YModalTxt = '是否退出该账号?'
				this.YModalShow = true
			},
			// 弹窗成功回调
			YModal_SubmitOk(e) {
				if (this.YModalTxt === '是否删除该账号信息？') {
					let DelInfo = JSON.parse(JSON.stringify( this.AccountList[this.CurrentSelDelAccountID]))
					// 静态修改（账号缓存数组）
					this.AccountList.splice(this.CurrentSelDelAccountID, 1) //删除
					
					// 当只剩一个账号缓存的时候
					if(this.AccountList.length<1){
						this.$pub.delStorageSync('Token')				// 清空操作
						this.$pub.delStorageSync('UserInfo') 			// 清空操作
						this.$pub.delStorageSync('AcclountList')		// 清空操作
						this.$pub.delStorageSync('Sts')					// 清空操作
						this.$pub.delStorageSync('HuanXinInfo')			// 清空操作
						this.$pub.reLaunch('/pages/other/login/index')
						return
					}
					
					// 如果删除是当前的账号那么切换到第一个账号
					if(DelInfo.Token === this.$pub.getStorageSync('Token')){
						this.AccountList[0].IsCheck = true 								// 切换到第一个账号
						this.$pub.delStorageSync('StudyPlane')							// 清空操作
						this.$pub.setStorageSync('Token',this.AccountList[0].Token)		// 替换token
						this.$pub.setStorageSync('UserInfo',this.AccountList[0].Info) 	// 替换用户的个人信息
						this.editIcon = !this.editIcon
						this.navRightTxt = '编辑'
						
						// 重等环信IM
						try{
							this.$HuanxinIM.close()
						}catch(e){
							console.log('初始化登录IM',e)
						}finally{
							setTimeout(async()=>{
								console.log('登录IM')
								// 登录IM
								let {msg,data} = await this.$HuanxinIM.Login({
									user:this.$pub.getStorageSync('UserInfo')._id,
									pwd: MD5(this.$pub.getStorageSync('UserInfo').pwd || this.$pub.getStorageSync('UserInfo').openid)
								})
								if(msg==='fail'){
									this.$pub.Toast('账号密码错误~',data)
									this.$pub.reLaunch('/pages/other/login/index')
								}
								console.log(data)
								this.$pub.setStorageSync('HuanXinInfo',data)
							},2500)
						}
					}
					
					// 同步到缓存内
					this.$pub.setStorageSync('AcclountList',this.AccountList)
				}else if (this.YModalTxt === '是否退出该账号?') {
					let indexS = this.AccountList.findIndex(i => i.Token == this.$pub.getStorageSync('Token'))
					this.AccountList.splice(indexS, 1) //删除
					this.$pub.delStorageSync('Token')				// 清空操作
					this.$pub.delStorageSync('UserInfo') 			// 清空操作
					this.$pub.delStorageSync('Sts')					// 清空操作
					this.$pub.delStorageSync('HuanXinInfo')			// 清空操作
					this.$pub.delStorageSync('StudyPlane')			// 清空操作
					this.AccountList.length!==0 ? this.$pub.setStorageSync('AcclountList',this.AccountList) : this.$pub.delStorageSync('AcclountList')
					
					this.$HuanxinIM.close()							// 断开连接
					this.$pub.reLaunch('/pages/other/login/index')
				}
			},
			// 删除账号缓存
			onDelAccont(e) {
				this.YModalTxt = '是否删除该账号信息？'
				this.YModalShow = true
				this.CurrentSelDelAccountID = this.AccountList.findIndex(i => i._id == e._id)
			}
		}
	}
</script>

<style scoped lang="less">
	.page {
		background-color: #f5f5f5;
	}

	.AccountBox {}

	.AccountBox-item {}

	.AccountBox-item-left {}

	.exitBox {}


	// 动画效果
	.cuIcon-roundclose {
		color: red;
		font-size: 40rpx;
		width: 40rpx;
		overflow: hidden;
		transition: width .6s;
	}

	.EditIconIsShow {
		width: 0;
	}
</style>
